package com.sihan.framework.etm.service.business.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.framework.exception.BusinessException;
import com.framework.model.ApiResult;
import com.framework.model.PageResult;
import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.PageUtils;
import com.framework.util.WebUtils;
import com.github.pagehelper.PageHelper;
import com.sihan.framework.etm.common.AppConfiguration;
import com.sihan.framework.etm.common.CacheOperatorInfo;
import com.sihan.framework.etm.common.CommonBiz;
import com.sihan.framework.etm.common.util.DateUtils;
import com.sihan.framework.etm.common.util.EtmWebUtil;
import com.sihan.framework.etm.dto.CommonQueryDTO;
import com.sihan.framework.etm.dto.business.ToolBorrowReturnRecordDTO;
import com.sihan.framework.etm.dto.business.ToolInWarehouseMasterDTO;
import com.sihan.framework.etm.dto.business.ToolPurchaseDTO;
import com.sihan.framework.etm.dto.business.ToolPurchaseDetailDTO;
import com.sihan.framework.etm.entity.DeviceSurplusTool;
import com.sihan.framework.etm.entity.User;
import com.sihan.framework.etm.entity.baseData.ToolModel;
import com.sihan.framework.etm.entity.business.PurchasePlanDetail;
import com.sihan.framework.etm.entity.business.PurchasePlanMaster;
import com.sihan.framework.etm.entity.business.ToolInWarehouseMaster;
import com.sihan.framework.etm.entity.business.ToolInWarehouseRecord;
import com.sihan.framework.etm.enums.CacheKeyName;
import com.sihan.framework.etm.enums.OperateType;
import com.sihan.framework.etm.mapper.CommonMapper;
import com.sihan.framework.etm.mapper.OrgMapper;
import com.sihan.framework.etm.mapper.UserMapper;
import com.sihan.framework.etm.mapper.baseData.ToolMapper;
import com.sihan.framework.etm.mapper.business.PurchasePlanDetailMapper;
import com.sihan.framework.etm.mapper.business.PurchasePlanMasterMapper;
import com.sihan.framework.etm.mapper.business.ToolInWarehouseMasterMapper;
import com.sihan.framework.etm.mapper.business.ToolInWarehouseRecordMapper;
import com.sihan.framework.etm.service.business.ToolPurchaseService;
import com.sihan.framework.etm.vo.CommonQueryResultVO;
import com.sihan.framework.etm.vo.OrgVO;
import com.sihan.framework.etm.vo.business.PurchasePlanDetailVO;
import com.sihan.framework.etm.vo.business.PurchasePlanMasterVO;
import com.sihan.framework.etm.vo.business.ToolInWarehouseDetailVO;
import com.sihan.framework.etm.vo.business.ToolInWarehouseStandingBookVO;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class ToolPurchaseServiceImpl extends BaseServiceImpl<PurchasePlanMaster, String> implements ToolPurchaseService{

	@Autowired
	private PurchasePlanMasterMapper purchasePlanMasterMapper;
	
	@Autowired
	private PurchasePlanDetailMapper purchasePlanDetailMapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private ToolInWarehouseMasterMapper toolInWarehouseMasterMapper;
	
	@Autowired
	private ToolInWarehouseRecordMapper toolInWarehouseRecordMapper;
	
	@Autowired
	private ToolMapper toolMapper;
	
	@Autowired
	private OrgMapper orgMapper;
	
	@Autowired
	private CommonBiz commonBiz;
	
	@Autowired
	private AppConfiguration appConfig;
	
	@Autowired
	private CommonMapper commonMapper;
	
	public static final Object lock = new Object();
	
	@Override
	public PageResult<PurchasePlanMasterVO> selectPage(ToolPurchaseDTO dto) {
		if(!StringUtils.isBlank(dto.getQueryStartTime())) {
			dto.setQueryStartTime(dto.getQueryStartTime() + " 00:00:00:000");
		}
		if(!StringUtils.isBlank(dto.getQueryEndTime())) {
			dto.setQueryEndTime(dto.getQueryEndTime() + " 23:59:59:999");
		}
		PageHelper.startPage(dto);
	    List<PurchasePlanMasterVO> result = purchasePlanMasterMapper.selectPage(dto);
	    if(null != result && !result.isEmpty()) {
	    	result.stream().forEach(vo->{
	    		vo.setCreateTime(vo.getCreateTime().substring(0, 19));
	    		vo.setSubmitTime(StringUtils.isBlank(vo.getSubmitTime())?"":vo.getSubmitTime().substring(0, 19));
	    		vo.setInWarehouseTime(StringUtils.isBlank(vo.getInWarehouseTime())?"":vo.getInWarehouseTime().substring(0, 10));
	    	});
	    }
	    return PageUtils.toPageResult(result);
	}

	@Override
	public void submitPlan(String id) {
		PurchasePlanMaster master = purchasePlanMasterMapper.selectById(id);
		if(null == master) {
			throw new BusinessException("传入计划id有误");
		}
		
		if(master.getPurchaseQuantity().compareTo(BigDecimal.ZERO) == 0) {
			throw new BusinessException("请添加计划明细");
		}
		
		if(master.getStatus() != 0) {
			throw new BusinessException("不可重复提交");
		}
		
		master.setStatus(1);
		master.setLastUpdateTime(new Date());
		master.setLastUpdateUser(WebUtils.username());
		master.setSubmitTime(new Date());
		purchasePlanMasterMapper.updateById(master);
	}

	@Override
	public void purchaseInWarehouse(String id, String warehouseTime) {
		PurchasePlanMaster master = purchasePlanMasterMapper.selectById(id);
		if(null == master) {
			throw new BusinessException("传入计划id有误");
		}
		
		if(master.getStatus() != 1) {
			throw new BusinessException("不可入库");
		}
		
		master.setStatus(2);
		master.setInWarehouseTime(StringUtils.isBlank(warehouseTime)?null:DateUtils.getInstance().getDateByStr(warehouseTime, DateUtils.getInstance().SDF_YM_DD2));
		master.setLastUpdateTime(new Date());
		master.setLastUpdateUser(WebUtils.username());
		purchasePlanMasterMapper.updateById(master);
		
	}

	@Override
	public List<PurchasePlanDetailVO> listPlanDetailByPlanId(ToolPurchaseDTO dto) {
		return purchasePlanMasterMapper.selectPlanDetailByPlanId(dto);
	}

	@Override
	@Transactional
	public void saveOrUpdatePlanDetail(ToolPurchaseDetailDTO dto) {
		if(null != dto.getPurchaseQuantity() && dto.getPurchaseQuantity().compareTo(new BigDecimal(99999999)) > 0) {
			throw new BusinessException("输入数字太大");
		}
		
		PurchasePlanDetail detail = new PurchasePlanDetail();
		if(!StringUtils.isBlank(dto.getId())) {
			detail = purchasePlanDetailMapper.selectById(dto.getId());
		}
		
		PurchasePlanMaster master = purchasePlanMasterMapper.selectById(dto.getPlanId()+"");
		if(null != master && master.getStatus() != 0) {
			throw new BusinessException("不可编辑");
		}
		
		if(null == master) {
			master = purchasePlanMasterMapper.selectById(detail.getPlanId()+"");
		}
		detail.setIsDelete(dto.getIsDelete());
		detail.setPurchaseQuantity(dto.getPurchaseQuantity());
		detail.setToolModelId(dto.getToolModelId()+"");
		detail.setPlanId(master.getId());
		purchasePlanDetailMapper.saveOrUpdate(detail);
		
		@SuppressWarnings("unchecked")
		List<PurchasePlanDetail> details = purchasePlanDetailMapper.selectList(
				new Condition<PurchasePlanDetail>().eq("is_delete", 0).eq("plan_id", detail.getPlanId()));
		if(null != details && !details.isEmpty()) {
			master.setPurchaseQuantity(details.stream().map(PurchasePlanDetail::getPurchaseQuantity).
					reduce(BigDecimal.ZERO, BigDecimal::add));
		}else {
			master.setPurchaseQuantity(BigDecimal.ZERO);
		}
		purchasePlanMasterMapper.updateById(master);
	}

	@Override
	public PurchasePlanMasterVO addPurchasePlan(String name, Integer type) {
		List<PurchasePlanDetailVO> needQuatity = new ArrayList<PurchasePlanDetailVO>();
		if(null != type && type == 1) {
			needQuatity = purchasePlanMasterMapper.selectNeedPurchaseToolQuatity();
			if(null != needQuatity && !needQuatity.isEmpty()) {
				List<PurchasePlanDetailVO> filterResult = needQuatity.stream().filter(
						v->v.getPurchaseQuantity().compareTo(BigDecimal.ZERO) > 0).
						collect(Collectors.toList());
				if(null == filterResult || filterResult.isEmpty()) {
					throw new BusinessException("没有采购计划需求");
				}
			}else {
				throw new BusinessException("没有采购计划需求");
			}
		}
		PurchasePlanMasterVO vo = new PurchasePlanMasterVO();
		PurchasePlanMaster master = new PurchasePlanMaster();
		master.setCreateTime(new Date());
		master.setCreateUser(WebUtils.username());
		master.setName(name);
		master.setStatus(0);
		master.setUserId(EtmWebUtil.userId());
		master.setPurchaseQuantity(BigDecimal.ZERO);
		purchasePlanMasterMapper.insert(master);
		if(null != type && type == 1) {
			if(null != needQuatity && !needQuatity.isEmpty()) {
				List<PurchasePlanDetailVO> filterResult = needQuatity.stream().filter(
						v->v.getPurchaseQuantity().compareTo(BigDecimal.ZERO) > 0).
						collect(Collectors.toList());
				if(null != filterResult && !filterResult.isEmpty()) {
					int sum = productPlanDetail(master.getId(),needQuatity);
					master.setPurchaseQuantity(new BigDecimal(sum));
					purchasePlanMasterMapper.updateById(master);
				}
			}
		}
		BeanUtils.copyProperties(master, vo);
		return vo;
	}
	
	private Integer productPlanDetail(String masterId,List<PurchasePlanDetailVO> needQuatity) {
		if(null != needQuatity && !needQuatity.isEmpty()) {
			needQuatity.stream().forEach(quatity->{
				PurchasePlanDetail detail = new PurchasePlanDetail();
				detail.setCreateTime(new Date());
				detail.setCreateUser(WebUtils.username());
				detail.setIsDelete(0);
				detail.setPlanId(masterId);
				detail.setPurchaseQuantity(quatity.getPurchaseQuantity());
				detail.setToolModelId(quatity.getToolModelId()+"");
				purchasePlanDetailMapper.insert(detail);
			});
			return needQuatity.stream().mapToInt(detail->detail.getPurchaseQuantity().intValue()).sum();
		}
		return null;
	}

	@Override
	public OrgVO toolBelongToOrg() {
		String userId = commonBiz.checkValidatedUserId();
		if(StringUtils.isBlank(userId)) {
			throw new BusinessException("请先识别身份");
		}
		return orgMapper.selectUserBelongOrg(userId);
	}

	@Override
	public void inWarehouseMaster(ToolInWarehouseMasterDTO dto) {
		//synchronized (lock) {
			//检查工器具名称是否重复
			int duplicateToolName = toolInWarehouseMasterMapper.checkToolNameHasDuplicate(dto.getModelId(), dto.getToolName());
			
			if(duplicateToolName > 0) {
				throw new BusinessException("工器具名称重复!");
			}
			
			String masterId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);
			log.info("开始主表-------------------------------------------------"+masterId);
			if(StringUtils.isBlank(masterId)) {
				ToolInWarehouseMaster master = new ToolInWarehouseMaster();
				User u = userMapper.selectById(commonBiz.checkValidatedUserId());
				master.setCreateTime(new Date());
				master.setCreateUser(null != u?u.getName():"");
				master.setOrgId(dto.getOrgId());
				toolInWarehouseMasterMapper.insert(master);
				//缓存入库主表id
				CacheOperatorInfo.setMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), master.getId());
				CacheOperatorInfo.setMapValue(CacheKeyName.BUSINESS_OPERATE_TYPE.getValue(), 
						OperateType.NEW_ADD_WAREHOUSE.getValue());
			}
			log.info("录入主表完成-------------------------------------------------"+ CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null));
			CacheOperatorInfo.setMapValue(CacheKeyName.CACHE_WAREHOUSE_IN_BELONG_INFO.getValue(), dto);
			//调用扫描接口
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_LOG.getValue(), CacheOperatorInfo.TOOL_CODE_READ_FLAG_ADD_NEW);
			CacheOperatorInfo.setMapValue(CacheKeyName.READER_CODE_LIST.getValue(), 
					CacheKeyName.READER_CODE_LIST.getValue());
			log.info("准备发送开启扫描------------------------------------------------");
			//开启打印机
			commonBiz.printStart();
			commonBiz.sendIvgScanStartCommand();
		//}
	}

	@Override
	public synchronized ToolInWarehouseDetailVO toolScanResult() {
		int tryCount = 1;
		String operatorId = commonBiz.checkValidatedUserId();
		if(StringUtils.isBlank(operatorId)) {
			commonBiz.sendIvgScanStopCommand();
			throw new BusinessException("操作失败，未检测到操作人员，请重新刷卡或者人脸识别");
		}
		Boolean hasExpired = false;
		Boolean hasDone = false;
		Date d = new Date();
		String masterId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);

		String oldCode = CacheKeyName.READER_CODE_LIST.getValue();
		
		ToolInWarehouseMasterDTO dto = (ToolInWarehouseMasterDTO)CacheOperatorInfo.getMapValue(
				CacheKeyName.CACHE_WAREHOUSE_IN_BELONG_INFO.getValue(), null);
		if(dto == null) {
			commonBiz.sendIvgScanStopCommand();
			throw new BusinessException("识别失败请重试");
		}
		
		hasExpired = false;
		d = new Date();
		while(!hasDone && !hasExpired) {
			oldCode = (String)CacheOperatorInfo.getMapValue(CacheKeyName.READER_CODE_LIST.getValue(), 
					CacheKeyName.READER_CODE_LIST.getValue());
			if(!StringUtils.isBlank(oldCode) && !oldCode.equals(CacheKeyName.READER_CODE_LIST.getValue())) {
				hasDone = true;
			}
			Calendar c = Calendar.getInstance();
			c.add(Calendar.SECOND, -appConfig.getWaitOperatorSeconds());
			if(c.getTime().compareTo(d) >= 0) {
				hasExpired = true;
			}
		}
		
		if(hasExpired) {
			commonBiz.sendIvgScanStopCommand();
			throw new BusinessException("请将工器具放置读写区域！并点击【开始识别】");
		}
		
		if(!StringUtils.isBlank(oldCode) && !oldCode.equals(CacheKeyName.READER_CODE_LIST.getValue())) {
			if(oldCode.split(",").length > 1) {
				commonBiz.sendIvgScanStopCommand();
				throw new BusinessException("一次只能入库一个工器具");
			}
			String tid = (String)CacheOperatorInfo.getMapValue(CacheKeyName.TID_VALUE.getValue(), CacheKeyName.TID_VALUE.getValue());
			
			//检查是否已经入库的标签
			List<String> duplicateCodes = toolInWarehouseMasterMapper.
					listHasDuplicateToolInWarehouse(tid,oldCode, masterId);
			if(null != duplicateCodes && !duplicateCodes.isEmpty()) {
				commonBiz.sendIvgScanStopCommand();
				throw new BusinessException("此标签已绑定工器具");
			}
			//synchronized (lock) {
//				@SuppressWarnings("unchecked")
//				ToolModel tool = toolMapper.selectOne(new Condition<ToolModel>().
//						eq("code", null).eq("type_id", dto.getModelId()).neq("status", 3));
			
				//分两种情况入库，工器具系统下发有编号和没编号的情况
				List<ToolModel> storageTools = null;
				Boolean hasToolName = false;
				String toolName = null;
				if(StringUtils.isBlank(dto.getToolName())) {
					storageTools = toolInWarehouseMasterMapper.listNoDeviceToolsByToolId(dto.getToolId(), masterId);
				}else {
					hasToolName = true;
					toolName = dto.getToolName();
					storageTools = toolInWarehouseMasterMapper.listNoDeviceTools(dto.getModelId(), masterId);
				}
				
				if(null == storageTools || storageTools.isEmpty()) {
					commonBiz.sendIvgScanStopCommand();
					throw new BusinessException("此工器具已入库，不要重复操作");
				}
				//生成新的RFID
				//String code = commonBiz.genarateToolCode(base.getModelCode(), 1).get(0);
				String code = storageTools.get(0).getCode();
				String chooseToolId = storageTools.get(0).getId();
				
				ToolInWarehouseDetailVO base = toolInWarehouseMasterMapper.
						selectScanToolBaseInfo(chooseToolId,masterId,dto.getUserId(),dto.getUseLocalId());
				//下发给设备
				if(tryCount > 1) {
					log.info("-------------------------重入：{}"+tryCount);
				}
				
				if(!StringUtils.isBlank(tid) && !tid.equals(CacheKeyName.TID_VALUE.getValue())) {
					commonBiz.sendIvgScanStopCommand();
					Boolean setResult = commonBiz.sendSetCodeCommand(tid,code);
					log.info("下发设置工器具编号命令：tid="+tid+",code="+code);
					if(!setResult) {
						//重试一次
						setResult = commonBiz.sendSetCodeCommand(tid,code);
						if(!setResult) {
							commonBiz.sendIvgScanStopCommand();
							throw new BusinessException("设置工器具编号失败，请重试");
						}
					}
					base.setOldCode(oldCode);
					base.setCode(code);
					if(!hasToolName) {
						toolName = storageTools.get(0).getName();
						base.setToolName(toolName);
					}
					
					@SuppressWarnings("unchecked")
					ToolInWarehouseRecord checkDuplicate = toolInWarehouseRecordMapper.selectOne(
							new Condition<ToolInWarehouseRecord>().eq("master_id", masterId).eq("tool_old_code", oldCode));
					if(null != checkDuplicate) {
						toolInWarehouseRecordMapper.deleteById(checkDuplicate.getId());
						log.info("已重复删除："+oldCode);
					}
					
					//查询是否已经有相同的入库记录
					@SuppressWarnings("unchecked")
					ToolInWarehouseRecord record = toolInWarehouseRecordMapper.selectOne(new Condition<>().
							eq("tool_code", code));
					
					if(null != record) {
						record.setMasterId(base.getId());
						record.setStatus(0);
						record.setToolCode(code);
						record.setToolOldCode(oldCode);
						record.setUserId(dto.getUserId());
						record.setToolName(base.getToolName());
						record.setToolId(chooseToolId);
						record.setProduceDate(base.getProduceDate());
						record.setInspectDate(base.getInspectDate());
						record.setTid(tid);
						record.setUseLocalId(dto.getUseLocalId());
						
						toolInWarehouseRecordMapper.updateById(record);
					}else {
						record = new ToolInWarehouseRecord();
						record.setMasterId(base.getId());
						record.setStatus(0);
						record.setToolCode(code);
						record.setToolOldCode(oldCode);
						record.setUserId(dto.getUserId());
						record.setToolName(base.getToolName());
						record.setToolId(chooseToolId);
						record.setProduceDate(base.getProduceDate());
						record.setInspectDate(base.getInspectDate());
						record.setTid(tid);
						record.setUseLocalId(dto.getUseLocalId());
						
						toolInWarehouseRecordMapper.insert(record);
					}
					
					commonBiz.sendIvgScanStopCommand();
					
					List<String> typeIds = new ArrayList<String>();
					typeIds.add(record.getTypeId());
					List<DeviceSurplusTool> surpluses = commonMapper.selectDeviceSurplusTools(typeIds);
					base.setBoxNum((null == surpluses || surpluses.isEmpty())?null:surpluses.get(0).getDeviceCode());
					return base;
				}
			}
		//}
		commonBiz.sendIvgScanStopCommand();
		throw new BusinessException("操作超时请重试");
	}

	@Override
	public void printToolCode(String code) {
		if(StringUtils.isBlank(code)) {
			throw new BusinessException("请输入正确的打印内容");
		}
		commonBiz.printCode(code);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public ApiResult submitInWarehouse() {
		String masterId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);
		ToolInWarehouseMaster master = toolInWarehouseMasterMapper.selectById(masterId);
		
		List<ToolInWarehouseRecord> records = toolInWarehouseRecordMapper.
				selectList(new Condition<ToolInWarehouseRecord>().eq("master_id", masterId));
		if(null == records || records.isEmpty()) {
			return ApiResult.fail("没有工器具可以入库");
		}
		
		//检查门锁状态
		ApiResult doorStat = commonBiz.confirmDeviceDoor();
		if(!doorStat.isSuccess()) {
			return doorStat;
		}
		
		//获取柜子中增量的工器具
		List<String> allAddCodes = (List<String>)CacheOperatorInfo.getMapValue(
				CacheKeyName.TOOL_WAIT_OPERATE_CODES.getValue(), new ArrayList<String>());
		//查询时间点之后盘点的工器具
		List<String> deviceTools = purchasePlanMasterMapper.selectToolAfterStartInwarehouse(DateUtils.getInstance().getDateStr(master.getCreateTime(), DateUtils.getInstance().SDF));
		
		if((null!= allAddCodes && !allAddCodes.isEmpty()) || (null != deviceTools && !deviceTools.isEmpty())) {
			List<String> inRecord = records.stream().map(ToolInWarehouseRecord::getToolCode).collect(Collectors.toList());
			if(!allAddCodes.containsAll(inRecord)) {
				//如果返回的入库数据为检查完成，那么判断当前库存数据是否已完全包含新增
				//库存中的工器具
				List<String> inDevices = toolMapper.queryAllCodesForDevice();
				if(!inDevices.containsAll(inRecord)) {
					return ApiResult.fail("请将所有工器具放入柜子中");
				}
			}

			String userId = commonBiz.checkValidatedUserId();
			if(!StringUtils.isBlank(userId)) {
				for(ToolInWarehouseRecord toolInRecord : records) {
					String deviceId = toolInWarehouseMasterMapper.selectInWarehouseDeviceIdByToolCode(toolInRecord.getToolCode());
					ToolModel tool = toolMapper.selectById(toolInRecord.getToolId());
					Date wareHouse = new Date();
					if(null != tool) {
						tool.setCode(toolInRecord.getToolCode());
						tool.setDeviceId(deviceId);
						tool.setRfidTid(toolInRecord.getTid());
						tool.setIsBind(0);
						tool.setOldCode(toolInRecord.getToolOldCode());
						tool.setStatus(0);
						tool.setName(toolInRecord.getToolName());
						tool.setMaintainUserId(toolInRecord.getUserId());
						tool.setUseRecordStatus(2);
						toolMapper.updateById(tool);
						toolInRecord.setToolId(tool.getId());
					}
					
					toolInRecord.setStatus(1);
					toolInRecord.setDeviceId(deviceId);
					toolInRecord.setInWarehouseTime(wareHouse);
					toolInWarehouseRecordMapper.updateById(toolInRecord);
				}
				if(null != master) {
					master.setStatus(1);
					toolInWarehouseMasterMapper.updateById(master);
				}
				CacheOperatorInfo.setMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);
				//发送关闭柜子的命令
				commonBiz.lockDevice();
				//关闭打印机
				commonBiz.printClose();	
				return ApiResult.success();
			}
		}else {
			return ApiResult.fail("请将所有工器具放入柜子中");
		}
		return ApiResult.fail();
	}

	@Override
	public PageResult<ToolInWarehouseStandingBookVO> warehouseStandingBook(ToolBorrowReturnRecordDTO dto) {
		if(!StringUtils.isBlank(dto.getQueryStartTime())) {
			dto.setQueryStartTime(dto.getQueryStartTime() + " 00:00:00:000");
		}
		if(!StringUtils.isBlank(dto.getQueryEndTime())) {
			dto.setQueryEndTime(dto.getQueryEndTime() + " 23:59:59:999");
		}
		PageHelper.startPage(dto);
	    List<ToolInWarehouseStandingBookVO> result = purchasePlanMasterMapper.warehouseStandingBook(dto);
	    if(null != result && result.size() > 0) {
	    	result.stream().forEach(vo->{
	    		vo.setInspectDate(StringUtils.isBlank(vo.getInspectDate())?"":vo.getInspectDate().substring(0, 10));
	    	    vo.setProduceDate(StringUtils.isBlank(vo.getProduceDate())?"":vo.getProduceDate().substring(0, 10));
	    	    vo.setInWarehouseDate(StringUtils.isBlank(vo.getInWarehouseDate())?"":vo.getInWarehouseDate().substring(0, 19));
	    	});
	    }
	    return PageUtils.toPageResult(result);
	}

	@Override
	public int checkToolHasDuplicate(String typeId, String toolName) {
		return toolInWarehouseMasterMapper.checkToolNameHasDuplicate(typeId, toolName);
	}

	@Override
	public List<CommonQueryResultVO> needAddToolList(CommonQueryDTO dto) {
		String masterId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);
		return commonMapper.selectNeedAddToolForPull(dto,masterId);
	}
	
	@Override
	public List<CommonQueryResultVO> needAddToolCode(CommonQueryDTO dto) {
		String masterId = (String)CacheOperatorInfo.getMapValue(CacheKeyName.BUSINESS_MASTER_ID.getValue(), null);
		return commonMapper.selectNeedAddToolCodeForPull(dto,masterId);
	}

}
